package com.jdd.modules.parkmonthly.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jdd.common.api.vo.Result;
import com.jdd.common.aspect.annotation.AutoLog;
import com.jdd.common.system.query.QueryGenerator;
import com.jdd.common.util.excel.entity.params.ExportParams;
import com.jdd.common.util.excel.web.entity.vo.NormalExcelConstants;
import com.jdd.common.util.excel.web.view.EasypoiSingleExcelView;
import com.jdd.modules.parking.entity.ParkInfo;
import com.jdd.modules.parking.service.IParkInfoService;
import com.jdd.modules.parkmonthly.entity.MonthlyCardEditInfo;
import com.jdd.modules.parkmonthly.service.IMonthlyCardEditInfoService;
import com.jdd.modules.parkmonthly.service.IMonthlyDepartmentService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @Description: 1
 * @Author: jdd
 * @Date: 2021-11-24
 * @Version: V1.0
 */
@Slf4j
@Api(tags = "1")
@RestController
@RequestMapping("/com/monthlyCardEditInfo")
public class MonthlyCardEditInfoController {

    @Resource
    private IMonthlyCardEditInfoService monthlyCardEditInfoService;
    @Resource
    private IMonthlyDepartmentService monthlyDepartmentService;
    @Resource
    private IParkInfoService parkInfoService;

    @Value("${parkInfo.parkCode}")
    private String parkCode;
    /**
     * 分页列表查询
     *
     * @param monthlyCardEditInfo
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "1-分页列表查询")
    @ApiOperation(value = "1-分页列表查询", notes = "1-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<MonthlyCardEditInfo>> queryPageList(MonthlyCardEditInfo monthlyCardEditInfo,
                                                            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                            @RequestParam(name = "opTime_begin", required = false) String opTimeBegin,
                                                            @RequestParam(name = "opTime_end", required = false) String opTimeEnd,
                                                            HttpServletRequest req) {
        log.info("传入参数----------------------------》:{}", monthlyCardEditInfo);

        Result<IPage<MonthlyCardEditInfo>> result = new Result<IPage<MonthlyCardEditInfo>>();

        //输入操作人模糊查询
        //可输入月租编号模糊查询
        //车主名称模糊查询
        //车牌号
        //车位号
        Map<String, String[]> parameterMap = req.getParameterMap();
        String createUserName = monthlyCardEditInfo.getCreateUserName();
        String monthlyCode = monthlyCardEditInfo.getMonthlyCode();
        String userName = monthlyCardEditInfo.getUserName();
        String plateNo = monthlyCardEditInfo.getPlateNos();
        String parkNumber = monthlyCardEditInfo.getParkNumbers();
        parameterMap.put("createUserName", null);
        parameterMap.put("monthlyCode", null);
        parameterMap.put("userName", null);
        parameterMap.put("plateNo", null);
        parameterMap.put("parkNumber", null);
        monthlyCardEditInfo.setCreateUserName(null);
        monthlyCardEditInfo.setMonthlyCode(null);
        monthlyCardEditInfo.setUserName(null);
        monthlyCardEditInfo.setPlateNos(null);
        monthlyCardEditInfo.setParkNumbers(null);

//		QueryWrapper<MonthlyCardEditInfo> queryWrapper = dealParamInfo(monthlyCardEditInfo);
        QueryWrapper<MonthlyCardEditInfo> queryWrapper = QueryGenerator.initQueryWrapper(monthlyCardEditInfo, parameterMap);

        queryWrapper.eq("park_code",parkCode);
        if (StringUtils.isNotEmpty(createUserName)) {
            queryWrapper.lambda().like(MonthlyCardEditInfo::getCreateUserName, createUserName);
        }
        if (StringUtils.isNotEmpty(monthlyCode)) {
            queryWrapper.lambda().like(MonthlyCardEditInfo::getMonthlyCode, monthlyCode);
        }
        if (StringUtils.isNotEmpty(userName)) {
            queryWrapper.lambda().like(MonthlyCardEditInfo::getUserName, userName);
        }
        if (StringUtils.isNotEmpty(plateNo)) {
            queryWrapper.lambda().like(MonthlyCardEditInfo::getPlateNos, plateNo);
        }
        if (StringUtils.isNotEmpty(parkNumber)) {
            queryWrapper.lambda().like(MonthlyCardEditInfo::getParkNumbers, parkNumber);
        }
        if (StringUtils.isNotEmpty(opTimeBegin)) {
            queryWrapper.ge("create_time", opTimeBegin);
        }
        if (StringUtils.isNotEmpty(opTimeEnd)) {
            queryWrapper.le("create_time", opTimeEnd);
        }
        queryWrapper.orderByDesc("create_time");
        Page<MonthlyCardEditInfo> page = new Page<MonthlyCardEditInfo>(pageNo, pageSize);
        IPage<MonthlyCardEditInfo> pageList = monthlyCardEditInfoService.page(page, queryWrapper);
        log.info("查询月卡操作记录表----------------------------》:{}", pageList);
        for (MonthlyCardEditInfo monthlyCardEditInfo1 : pageList.getRecords()) {
            //根据部门id查询当前部门的所有上级部门并拼接返回
            String departmentNameChain = monthlyDepartmentService.getDepartmentNameChain(monthlyCardEditInfo1.getMonthlyDepartmentId());
            monthlyCardEditInfo1.setMonthlyDepartmentName(departmentNameChain);
        }
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }

    /**
     * 处理前端参数，供查询导出使用
     *
     * @param monthlyCardEditInfo
     * @return
     */
    public QueryWrapper<MonthlyCardEditInfo> dealParamInfo(MonthlyCardEditInfo monthlyCardEditInfo) {
        QueryWrapper<MonthlyCardEditInfo> queryWrapper = new QueryWrapper<>();

        queryWrapper.eq("park_code", parkCode);
        if (StringUtils.isNotEmpty(monthlyCardEditInfo.getUserName())) {
            queryWrapper.like("user_name", monthlyCardEditInfo.getUserName());
        }
        if (StringUtils.isNotEmpty(monthlyCardEditInfo.getOptionsType())) {
            queryWrapper.eq("options_type", monthlyCardEditInfo.getOptionsType());
        }
        if (StringUtils.isNotEmpty(monthlyCardEditInfo.getUpdateUserName())) {
            queryWrapper.like("update_user_name", monthlyCardEditInfo.getUpdateUserName());
        }
        if (StringUtils.isNotEmpty(monthlyCardEditInfo.getMonthlyCode())) {
            queryWrapper.like("monthly_code", monthlyCardEditInfo.getMonthlyCode());
        }
        if (StringUtils.isNotEmpty(monthlyCardEditInfo.getPlateNos())) {
            queryWrapper.like("plate_nos", monthlyCardEditInfo.getPlateNos());
        }
        if (StringUtils.isNotEmpty(monthlyCardEditInfo.getParkNumbers())) {
            queryWrapper.eq("park_numbers", monthlyCardEditInfo.getParkNumbers());
        }
        if (StringUtils.isNotEmpty(monthlyCardEditInfo.getMonthlyCardId())) {
            queryWrapper.eq("monthly_card_id", monthlyCardEditInfo.getMonthlyCardId());
        }
        if (null != monthlyCardEditInfo.getStartTime()) {
            queryWrapper.ge("create_time", monthlyCardEditInfo.getStartTime());
        }
        if (null != monthlyCardEditInfo.getEndTime()) {
            queryWrapper.le("create_time", monthlyCardEditInfo.getEndTime());
        }
        queryWrapper.orderByDesc("create_time");
        return queryWrapper;
    }

    /**
     * 添加
     *
     * @param monthlyCardEditInfo
     * @return
     */
    @AutoLog(value = "1-添加")
    @ApiOperation(value = "1-添加", notes = "1-添加")
    @PostMapping(value = "/add")
    public Result<MonthlyCardEditInfo> add(@RequestBody MonthlyCardEditInfo monthlyCardEditInfo) {
        Result<MonthlyCardEditInfo> result = new Result<MonthlyCardEditInfo>();
        try {
            monthlyCardEditInfoService.save(monthlyCardEditInfo);
            result.success("添加成功！");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("操作失败");
        }
        return result;
    }

    /**
     * 编辑
     *
     * @param monthlyCardEditInfo
     * @return
     */
    @AutoLog(value = "1-编辑")
    @ApiOperation(value = "1-编辑", notes = "1-编辑")
    @PutMapping(value = "/edit")
    public Result<MonthlyCardEditInfo> edit(@RequestBody MonthlyCardEditInfo monthlyCardEditInfo) {
        Result<MonthlyCardEditInfo> result = new Result<MonthlyCardEditInfo>();
        MonthlyCardEditInfo monthlyCardEditInfoEntity = monthlyCardEditInfoService.getById(monthlyCardEditInfo.getId());
        if (monthlyCardEditInfoEntity == null) {
            result.error500("未找到对应实体");
        } else {
            boolean ok = monthlyCardEditInfoService.updateById(monthlyCardEditInfo);
            if (ok) {
                result.success("修改成功!");
            }
        }

        return result;
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "1-通过id删除")
    @ApiOperation(value = "1-通过id删除", notes = "1-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        try {
            monthlyCardEditInfoService.removeById(id);
        } catch (Exception e) {
            log.error("删除失败", e.getMessage());
            return Result.error("删除失败!");
        }
        return Result.ok("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "1-批量删除")
    @ApiOperation(value = "1-批量删除", notes = "1-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<MonthlyCardEditInfo> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        Result<MonthlyCardEditInfo> result = new Result<MonthlyCardEditInfo>();
        if (ids == null || "".equals(ids.trim())) {
            result.error500("参数不识别！");
        } else {
            this.monthlyCardEditInfoService.removeByIds(Arrays.asList(ids.split(",")));
            result.success("删除成功!");
        }
        return result;
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "1-通过id查询")
    @ApiOperation(value = "1-通过id查询", notes = "1-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<MonthlyCardEditInfo> queryById(@RequestParam(name = "id", required = true) String id) {
        Result<MonthlyCardEditInfo> result = new Result<MonthlyCardEditInfo>();
        MonthlyCardEditInfo monthlyCardEditInfo = monthlyCardEditInfoService.getById(id);
        if (monthlyCardEditInfo == null) {
            result.error500("未找到对应实体");
        } else {
            result.setResult(monthlyCardEditInfo);
            result.setSuccess(true);
        }
        return result;
    }

    /**
     * 导出excel
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, HttpServletResponse response, MonthlyCardEditInfo monthlyCardEditInfo,
                                  @RequestParam(name = "opTime_begin", required = false) String opTimeBegin,
                                  @RequestParam(name = "opTime_end", required = false) String opTimeEnd) {
        // Step.1 组装查询条件
//       QueryWrapper<MonthlyCardEditInfo> queryWrapper =dealParamInfo(monthlyCardEditInfo);
        QueryWrapper<MonthlyCardEditInfo> queryWrapper = QueryGenerator.initQueryWrapper(monthlyCardEditInfo, request.getParameterMap());

        queryWrapper.eq("park_code", parkCode);
        if (StringUtils.isNotEmpty(opTimeBegin)) {
            queryWrapper.ge("create_time", opTimeBegin);
        }
        if (StringUtils.isNotEmpty(opTimeEnd)) {
            queryWrapper.le("create_time", opTimeEnd);
        }
        queryWrapper.orderByDesc("create_time");

        //Step.2 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new EasypoiSingleExcelView());
        List<MonthlyCardEditInfo> monthlyCardEditInfos = monthlyCardEditInfoService.list(queryWrapper);
        log.info("================>:{}", monthlyCardEditInfos);
        for (MonthlyCardEditInfo monthlyCardEditInfo1 : monthlyCardEditInfos) {
            if (null != monthlyCardEditInfo1.getOptionsType()) {
                switch (monthlyCardEditInfo1.getOptionsType()) {
                    case "1":
                        monthlyCardEditInfo1.setOptionsType("储值车充值");
                        break;
                    case "2":
                        monthlyCardEditInfo1.setOptionsType("月卡延期");
                        break;
                    case "3":
                        monthlyCardEditInfo1.setOptionsType("月卡注销");
                        break;
                    case "4":
                        monthlyCardEditInfo1.setOptionsType("月卡开通");
                        break;
                    case "5":
                        monthlyCardEditInfo1.setOptionsType("月卡修改");
                        break;
                    case "6":
                        monthlyCardEditInfo1.setOptionsType("月卡报停");
                        break;
                    case "7":
                        monthlyCardEditInfo1.setOptionsType("月卡激活");
                        break;
                    default:
                        monthlyCardEditInfo1.setOptionsType("未知");
                        break;
                }
            }
            if (null != monthlyCardEditInfo1.getBusinessSource()) {
                switch (monthlyCardEditInfo1.getBusinessSource()) {
                    case "1":
                        monthlyCardEditInfo1.setBusinessSource("人工");
                        break;
                    case "2":
                        monthlyCardEditInfo1.setBusinessSource("车主用户");
                        break;
                    case "3":
                        monthlyCardEditInfo1.setBusinessSource("第三方对接");
                        break;
                    default:
                        monthlyCardEditInfo1.setBusinessSource("未知");
                        break;
                }
            }

            if (null != monthlyCardEditInfo1.getPaymentChannel()) {
                switch (monthlyCardEditInfo1.getPaymentChannel()) {
                    case "1":
                        monthlyCardEditInfo1.setPaymentChannel("现金");
                        break;
                    case "2":
                        monthlyCardEditInfo1.setPaymentChannel("工行");
                        break;
                    case "3":
                        monthlyCardEditInfo1.setPaymentChannel("微信");
                        break;
                    case "4":
                        monthlyCardEditInfo1.setPaymentChannel("支付宝");
                        break;
                    default:
                        monthlyCardEditInfo1.setPaymentChannel("未知");
                        break;
                }
            }

            if (null != monthlyCardEditInfo1.getOverdueDelayWay()) {
                switch (monthlyCardEditInfo1.getOverdueDelayWay()) {
                    case "1":
                        monthlyCardEditInfo1.setOverdueDelayWay("顺延");
                        break;
                    case "2":
                        monthlyCardEditInfo1.setOverdueDelayWay("跳延");
                        break;
                    default:
                        monthlyCardEditInfo1.setOverdueDelayWay("未知");
                        break;
                }
            }
        }
        //导出文件名称
        mv.addObject(NormalExcelConstants.FILE_NAME, "1列表");
        mv.addObject(NormalExcelConstants.CLASS, MonthlyCardEditInfo.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("月卡操作信息表", "导出信息"));
        mv.addObject(NormalExcelConstants.DATA_LIST, monthlyCardEditInfos);
        return mv;
    }


}
